//
//  HMRefreshControl.swift
//  webo
//
//  Created by apple on 2016/11/18.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
let refrechHeigt = 60
enum refreshstate: Int {
    case normal = 0
    case already
    case refreshing
}
class HMRefreshControl: UIControl {

    var restatus: refreshstate = .normal {
        didSet{
            switch restatus {
                
            case .normal:
                lb_text.text = "继续往下拉刷新"
                iv_direction.transform = CGAffineTransform.identity
                if oldValue == .refreshing {
                    UIView.animate(withDuration: 0.25, animations: {
                      self.scrollview?.contentInset.top = self.scrollview!.contentInset.top - CGFloat(refrechHeigt)
                    }, completion: { (make) in
                        self.iv_direction.isHidden = false

                    })
                }
                
            case .already:
                lb_text.text = "准备刷新"
                iv_direction.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
            case .refreshing:
                lb_text.text = "正在刷新"
                indicator.startAnimating()
//                lb_text.isHidden = true
                iv_direction.isHidden = true
                sendActions(for: .valueChanged)
                
                UIView.animate(withDuration: 0.25, animations: {
                    self.scrollview?.contentInset.top = self.scrollview!.contentInset.top + CGFloat(refrechHeigt)
                })
                
            }
        }
        
    }
    
    func endAnimation(){
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5 ) {
            self.restatus = .normal
        }
        indicator.stopAnimating()
    }
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refrechHeigt, width: Int(ScreenWidth), height: refrechHeigt)
        super.init(frame: rect)
        setupUI()
        self.backgroundColor = UIColor.red
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        self.addSubview(backView)
        self.addSubview(lb_text)
        self.addSubview(iv_direction)
        self.addSubview(indicator)
        
        backView.snp.makeConstraints { (make) in
          make.left.right.bottom.equalTo(self)
        }
        lb_text.snp.makeConstraints { (make) in
            make.leading.equalTo(self.snp.centerX).offset(5)
            make.centerY.equalTo(self)
        }
        iv_direction.snp.makeConstraints { (make) in
            make.trailing.equalTo(self.snp.centerX).offset(-10)
            make.centerY.equalTo(self)
        }
        indicator.snp.makeConstraints { (make) in
            make.center.equalTo(iv_direction)
        }
        
        
    }
//    文字
    private lazy var lb_text: UILabel = UILabel(text: "正在刷新", fontSize: 12, numbLines: 0, tcolor:UIColor.gray)
    private lazy var iv_direction = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    fileprivate  var scrollview: UIScrollView?
   private var indicator:UIActivityIndicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    private lazy var backView:UIImageView = UIImageView(image: #imageLiteral(resourceName: "refreshbg"))
    deinit {
        scrollview?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}

//在什么时候设置KVO观察   -> 当刷新控件被添加到父视图上的时候开始设置KVO观察
extension HMRefreshControl{
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        if let newView = newSuperview as? UIScrollView {
            scrollview = newView
            scrollview?.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        }
        
    }
    
    //观察的监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let offset = scrollview?.contentOffset.y ?? 0
        let targetOffset = -(CGFloat( refrechHeigt) + self.scrollview!.contentInset.top)
        
        if scrollview!.isDragging {
            if restatus == .normal && offset < targetOffset{
                print("准备刷新")
                restatus = .already
            }else if(restatus == .already && offset > targetOffset){
                print("下下拖")
                restatus = .normal
            }
        }else{
            if restatus == .already{
                restatus = .refreshing
            }
        }

        
    }
    

    
    

}
